package _10_working_with_streaming_io

import akka.actor.ActorSystem
import akka.stream._
import akka.stream.scaladsl.Tcp.{IncomingConnection, ServerBinding}
import akka.stream.scaladsl._
import akka.util.ByteString

import scala.concurrent._

object REPLClient extends App {

  implicit val system       = ActorSystem("Tcp")
  implicit val materializer = ActorMaterializer()
  implicit val ec           = system.dispatcher

  val connection = Tcp().outgoingConnection("127.0.0.1", 8888)

  val replParser =
    Flow[String].takeWhile(_ != "q")
    .concat(Source.single("BYE"))
    .map(elem => ByteString(s"$elem\n"))

  val repl = Flow[ByteString]
             .via(Framing.delimiter(
               ByteString("\n"),
               maximumFrameLength = 256,
               allowTruncation = true
             ))
             .map(_.utf8String)
             .map(text => println("Server: " + text))
             .map(_ => readLine("> "))
             .via(replParser)

  connection.join(repl).run()
}
